<template>
  <div class="ai-chat">
    <div class="chat-header">
      <div class="header-left">
        <h3>AI 日志分析助手</h3>
        <!-- 当前对话指示器 -->
        <div v-if="currentConversationId" class="current-conversation-indicator">
          <span class="conversation-label">当前对话:</span>
          <span class="conversation-name">
            {{ getCurrentConversationName() }}
          </span>
        </div>
      </div>
      <div class="header-actions">
        <div class="model-selector">
          <label>当前模型：</label>
          <select v-model="currentModelKey" @change="changeModel" class="model-select">
            <option 
              v-for="model in availableModels" 
              :key="model.key" 
              :value="model.key"
            >
              {{ model.name }}
            </option>
          </select>
        </div>
        <button @click="analyzeLogs" :disabled="analyzing" class="btn btn-secondary">
          {{ analyzing ? '分析中...' : '概览分析' }}
        </button>
        <button @click="analyzeLogsWithNewSession" :disabled="analyzing" class="btn btn-outline">
          新建分析
        </button>
        <button @click="clearHistory" class="btn btn-outline">
          清空历史
        </button>
      </div>
    </div>

    <!-- 对话会话列表 -->
    <div v-if="conversationSessions.length > 0" class="conversation-sessions">
      <h4>对话会话</h4>
      <div class="session-list">
        <div 
          v-for="session in conversationSessions" 
          :key="session.id"
          :class="['session-item', { 'active': session.id === currentConversationId }]"
          @click="switchConversation(session.id)"
        >
          <div class="session-title">{{ session.title }}</div>
          <div class="session-time">{{ formatTime(session.timestamp) }}</div>
        </div>
      </div>
    </div>

    <!-- 聊天界面 -->
    <div class="chat-container">
      <div class="chat-messages" ref="messagesContainer">
        <div
          v-for="(message, index) in conversationHistory"
          :key="index"
          :class="['message', message.type]"
        >
          <div class="message-content">
            <div class="message-text markdown-content" v-html="renderMarkdown(message.content)"></div>
            <div v-if="message.type === 'ai' && message.content === '' && asking" class="typing-indicator">
              <span class="dot"></span>
              <span class="dot"></span>
              <span class="dot"></span>
            </div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
        
        <!-- 建议问题显示在聊天区域 -->
        <div v-if="suggestedQuestions.length > 0 && currentConversationId" class="suggested-questions-in-chat">
          <div class="suggested-questions-header">建议问题：</div>
          <div class="question-list">
            <button
              v-for="(question, index) in suggestedQuestions"
              :key="index"
              @click="askQuestion(question)"
              class="question-btn"
            >
              {{ question }}
            </button>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input">
        <div class="input-container">
          <div class="prefix-selector">
            <button @click="showPrefixDialog = true" class="prefix-btn">
              <span class="prefix-icon">⌘</span>
              问答前缀
            </button>
          </div>
          <textarea
            v-model="currentQuestion"
            @keydown.enter.prevent="sendQuestion"
            placeholder="请输入您的问题..."
            class="question-input"
            rows="3"
          ></textarea>
          <button @click="sendQuestion" :disabled="!currentQuestion.trim() || asking" class="send-btn">
            {{ asking ? '发送中...' : '发送' }}
          </button>
        </div>
      </div>
      
      <!-- 前缀选择对话框 -->
      <div v-if="showPrefixDialog" class="config-dialog">
        <div class="dialog-content prefix-dialog">
          <h4>选择问答前缀</h4>
          <div class="prefix-list">
            <div 
              class="prefix-item"
              @click="selectPrefix('/dsl')"
            >
              <div class="prefix-name">/dsl</div>
              <div class="prefix-description">
                DSL查询模式 - 用于查找和理解日志分析流程
                <div class="prefix-example">例如：/dsl 网口初始化失败了，怎么处理？</div>
              </div>
            </div>
          </div>
          <div class="dialog-actions">
            <button @click="showPrefixDialog = false" class="btn btn-secondary">取消</button>
          </div>
        </div>
      </div>
    </div>

    <!-- AI配置对话框 -->
    <div v-if="showConfigDialog" class="config-dialog">
      <div class="dialog-content">
        <h4>AI 配置</h4>
        <div class="config-form">
          <div class="form-group">
            <label>AI提供商：</label>
            <select v-model="aiConfig.provider">
              <option value="openai">OpenAI</option>
              <option value="claude">Claude</option>
              <option value="local">本地LM模型</option>
            </select>
          </div>
          <div class="form-group">
            <label>API密钥：</label>
            <input type="password" v-model="aiConfig.api_key" placeholder="本地模型可不填">
          </div>
          <div class="form-group">
            <label>模型：</label>
            <input v-model="aiConfig.model" placeholder="模型名称，如：google/gemma-3-4b">
          </div>
          <div class="form-group">
            <label>最大Token数：</label>
            <input type="number" v-model="aiConfig.max_tokens" min="-1" max="4000" placeholder="-1表示无限制">
          </div>
          <div class="form-group">
            <label>温度：</label>
            <input type="number" v-model="aiConfig.temperature" min="0" max="2" step="0.1">
          </div>
          <div class="form-group">
            <label>API地址：</label>
            <input v-model="aiConfig.base_url" placeholder="API地址，如：http://localhost:1234">
          </div>
        </div>
        <div class="dialog-actions">
          <button @click="saveConfig" class="btn btn-primary">保存</button>
          <button @click="showConfigDialog = false" class="btn btn-secondary">取消</button>
        </div>
      </div>
    </div>

    <!-- 配置按钮 -->
    <div class="config-button">
      <button @click="showConfigDialog = true" class="btn btn-outline">
        配置AI
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { marked } from 'marked'
import { ElMessage } from 'element-plus'
import { 
  aiAnalyze, 
  aiAskStream, 
  getConversationHistory, 
  clearConversationHistory,
  getAIConfig,
  updateAIConfig,
  getAIModels,
  setCurrentAIModel,
  getSessionConversations,
  clearSessionConversations
} from '@/api'
import { useWorkspaceStore } from '@/stores/workspace'

// 响应式数据
const initialAnalysis = ref('')
const suggestedQuestions = ref<string[]>([])
const conversationHistory = ref<Array<{
  type: 'user' | 'ai'
  content: string
  timestamp: string
}>>([])
const currentQuestion = ref('')
const analyzing = ref(false)
const asking = ref(false)
const showConfigDialog = ref(false)
const showPrefixDialog = ref(false)
const messagesContainer = ref<HTMLElement>()

// 多轮对话相关
const currentConversationId = ref<string | null>(null)
const conversationSessions = ref<Array<{
  id: string
  title: string
  timestamp: string
}>>([])

// AI配置
const aiConfig = ref({
  provider: 'local',
  api_key: '',
  model: 'google/gemma-3-4b',
  max_tokens: -1,
  temperature: 0.7,
  base_url: 'http://localhost:1234'
})

// 模型选择相关
const availableModels = ref<Array<{
  key: string
  name: string
  provider: string
  is_current: boolean
}>>([])
const currentModelKey = ref('local')

// 获取workspace store
const workspaceStore = useWorkspaceStore()

// 获取当前session ID用于对话保存
const currentSessionId = computed(() => workspaceStore.currentSession?.id || null)

// 方法
const analyzeLogs = async () => {
  analyzing.value = true
  try {
    const response = await aiAnalyze()
    
    // 检查是否有当前session
    const hasCurrentSession = currentSessionId.value !== null
    
    if ((response as any).initial_analysis) {
      // 将分析结果放到对话框中
      if (!hasCurrentSession) {
        // 如果没有当前session，创建新的对话会话（前端临时）
        currentConversationId.value = new Date().toISOString()
        const sessionTitle = '日志分析'
        conversationSessions.value.push({
          id: currentConversationId.value,
          title: sessionTitle,
          timestamp: new Date().toISOString()
        })
      }
      
      // 添加AI分析结果到对话历史
      conversationHistory.value.push({
        type: 'ai',
        content: (response as any).initial_analysis,
        timestamp: new Date().toISOString()
      })
      
      // 清空初始分析显示
      initialAnalysis.value = ''
    }
    
    if ((response as any).suggested_questions) {
      suggestedQuestions.value = (response as any).suggested_questions
    }
    
    // 滚动到底部
    await scrollToBottom()
  } catch (error: any) {
    console.error('分析失败:', error)
    console.error('错误详情:', error.response?.data || error.message)
    ElMessage.error(`分析失败: ${error.response?.data?.error || error.message}`)
  } finally {
    analyzing.value = false
  }
}

const analyzeLogsWithNewSession = async () => {
  // 强制创建新会话进行分析
  currentConversationId.value = null
  conversationHistory.value = []
  initialAnalysis.value = ''
  suggestedQuestions.value = []
  
  await analyzeLogs()
}

const askQuestion = async (question: string) => {
  if (!question.trim()) return

  // 添加用户消息
  conversationHistory.value.push({
    type: 'user',
    content: question,
    timestamp: new Date().toISOString()
  })

  asking.value = true
  currentQuestion.value = ''

  // 添加AI消息占位符
  const aiMessageIndex = conversationHistory.value.length
  conversationHistory.value.push({
    type: 'ai',
    content: '',
    timestamp: new Date().toISOString()
  })

  try {
    
    // 使用流式API，传递当前session ID
    await aiAskStream(
      question,
      // onChunk: 接收每个数据块
      (chunk: string) => {
        try {
          // 尝试解析为JSON
          const response = JSON.parse(chunk)
          
          // 检查是否是DSL响应
          if (response.type) {
            switch (response.type) {
              case 'start':
                // 开始处理DSL查询
                conversationHistory.value[aiMessageIndex].content = '⏳ ' + response.content
                break
                
              case 'dsl_result':
                // 处理DSL查询结果
                const dslResponse = response.content
                let formattedContent = '### DSL查询结果\n\n'
                
                if (dslResponse.success) {
                  const result = dslResponse.result
                  
                  // 第一阶段：AI思考过程
                  formattedContent += '### 1️⃣ AI思考过程\n\n'
                  formattedContent += result.thinking_process + '\n\n'
                  
                  // 第二阶段：Flow执行结果
                  formattedContent += '### 2️⃣ Flow执行结果\n\n'
                  const execResult = result.execution_result
                  
                  // 执行状态
                  formattedContent += `**最终状态**：${execResult.final_state || '未知'}\n`
                  if (execResult.final_message) {
                    formattedContent += `**状态信息**：${execResult.final_message}\n`
                  }
                  if (execResult.evidence_count !== null) {
                    formattedContent += `**证据数量**：${execResult.evidence_count}\n`
                  }
                  
                  // 执行轨迹
                  if (execResult.trace && execResult.trace.length > 0) {
                    formattedContent += '\n**执行轨迹**：\n```mermaid\nstateDiagram-v2\n'
                    let prevState = null
                    for (const trace of execResult.trace) {
                      const parts = trace.split('->').map(p => p.trim())
                      if (parts.length >= 2) {
                        const action = parts[0]
                        const state = parts[1].split('|')[0].trim()
                        const stateId = state.replace(/[^a-zA-Z0-9]/g, '_')
                        formattedContent += `  ${stateId}: ${state}\n`
                        if (prevState) {
                          formattedContent += `  ${prevState} --> ${stateId}\n`
                        }
                        prevState = stateId
                      }
                    }
                    formattedContent += '```\n'
                  }
                  
                  // 第三阶段：AI分析结果
                  formattedContent += '\n### 3️⃣ AI分析结果\n\n'
                  formattedContent += result.analysis + '\n\n'
                  
                  // Flow详情（折叠）
                  formattedContent += '<details>\n'
                  formattedContent += '<summary>📄 Flow详情</summary>\n\n'
                  formattedContent += '```yaml\n'
                  formattedContent += JSON.stringify(result.matched_flow, null, 2)
                  formattedContent += '\n```\n'
                  formattedContent += '</details>'
                } else {
                  formattedContent += `❌ 查询失败：${dslResponse.error}\n`
                  if (dslResponse.raw_response) {
                    formattedContent += `\n原始响应：${dslResponse.raw_response}`
                  }
                }
                
                conversationHistory.value[aiMessageIndex].content = formattedContent
                break
                
              case 'end':
                // DSL查询完成
                conversationHistory.value[aiMessageIndex].content += '\n\n---\n' + 
                  '✅ ' + response.content
                break
                
              default:
                // 未知类型，作为普通文本处理
                conversationHistory.value[aiMessageIndex].content += chunk
            }
          } else {
            // 不是带类型的响应，作为普通文本处理
            conversationHistory.value[aiMessageIndex].content += chunk
          }
        } catch (e) {
          // JSON解析失败，作为普通文本处理
          conversationHistory.value[aiMessageIndex].content += chunk
        }
        
        // 每次更新后滚动到底部
        scrollToBottom()
      },
      // onEnd: 流式输出结束
      () => {
        asking.value = false
        scrollToBottom()
      },
      // onError: 发生错误
      (error: string) => {
        conversationHistory.value[aiMessageIndex].content = `错误: ${error}`
        asking.value = false
        scrollToBottom()
      },
      (currentSessionId.value ?? undefined),
      false // includeLogs 始终为 false
    )
  } catch (error) {
    console.error('发送问题失败:', error)
    conversationHistory.value[aiMessageIndex].content = `发送问题失败: ${error}`
    asking.value = false
    await scrollToBottom()
  }
}

const sendQuestion = async () => {
  if (!currentQuestion.value.trim() || asking.value) return

  const question = currentQuestion.value.trim()
  
  // 使用当前会话ID，如果没有则使用默认值
  const sessionId = currentSessionId.value || 'default'
  
  // 添加用户消息
  conversationHistory.value.push({
    type: 'user',
    content: question,
    timestamp: new Date().toISOString()
  })

  asking.value = true
  currentQuestion.value = ''

  // 添加AI消息占位符
  const aiMessageIndex = conversationHistory.value.length
  conversationHistory.value.push({
    type: 'ai',
    content: '',
    timestamp: new Date().toISOString()
  })

  try {
    
    // 使用流式API，传入当前会话ID
    await aiAskStream(
      question,
      // onChunk: 接收每个数据块
      (chunk: string) => {
        conversationHistory.value[aiMessageIndex].content += chunk
        scrollToBottom()
      },
      // onEnd: 流式输出结束
      () => {
        asking.value = false
        scrollToBottom()
      },
      // onError: 发生错误
      (error: string) => {
        conversationHistory.value[aiMessageIndex].content = `错误: ${error}`
        asking.value = false
        scrollToBottom()
      },
      sessionId,
      false // includeLogs 始终为 false
    )
  } catch (error) {
    console.error('发送问题失败:', error)
    conversationHistory.value[aiMessageIndex].content = `发送问题失败: ${error}`
    asking.value = false
    await scrollToBottom()
  }
}

const clearHistory = async () => {
  try {
    if (currentSessionId.value) {
      // 使用持久化API清空当前会话的对话历史
      await clearSessionConversations(currentSessionId.value)
    } else {
      // 兼容旧版本：清空内存中的对话历史
      await clearConversationHistory()
    }
    conversationHistory.value = []
    initialAnalysis.value = ''
    suggestedQuestions.value = []
    currentConversationId.value = null
    conversationSessions.value = []
  } catch (error) {
    console.error('清空历史失败:', error)
  }
}

const switchConversation = async (conversationId: string) => {
  try {
    currentConversationId.value = conversationId
    
    // 加载该对话的历史
    const response = await getConversationHistory(conversationId)
    conversationHistory.value = []
    
    // 将历史记录转换为前端格式
    for (const item of (response as unknown as any[])) {
      conversationHistory.value.push({
        type: 'user',
        content: item.question,
        timestamp: item.timestamp
      })
      conversationHistory.value.push({
        type: 'ai',
        content: item.answer,
        timestamp: item.timestamp
      })
    }
    
    await scrollToBottom()
  } catch (error) {
    console.error('切换对话失败:', error)
  }
}

const startNewConversation = () => {
  currentConversationId.value = null
  conversationHistory.value = []
  initialAnalysis.value = ''
  suggestedQuestions.value = []
}

const loadConversationHistory = async () => {
  try {
    // 如果有当前会话ID，使用持久化API
    if (currentSessionId.value) {
      const response = await getSessionConversations(currentSessionId.value)
      conversationHistory.value = []
      
      // 将历史记录转换为前端格式
      for (const item of (response as unknown as any[])) {
        conversationHistory.value.push({
          type: item.message_type,
          content: item.content,
          timestamp: item.timestamp
        })
      }
    } else {
      // 兼容旧版本：使用内存中的对话历史
      const response = await getConversationHistory()
      const userMessages = (response as unknown as any[]).map((item: any) => ({
        type: 'user' as const,
        content: item.question,
        timestamp: item.timestamp
      }))
      const aiMessages = (response as unknown as any[]).map((item: any) => ({
        type: 'ai' as const,
        content: item.answer,
        timestamp: item.timestamp
      }))
      conversationHistory.value = [...userMessages, ...aiMessages]
    }
  } catch (error) {
    console.error('加载对话历史失败:', error)
  }
}

const loadAIConfig = async () => {
  try {
    const response = await getAIConfig()
    aiConfig.value = { ...aiConfig.value, ...response }
  } catch (error) {
    console.error('加载AI配置失败:', error)
  }
}

const loadAvailableModels = async () => {
  try {
    const response = await getAIModels()
    availableModels.value = response as unknown as any[]
    // 设置当前模型
    const currentModel = (response as unknown as any[]).find((model: any) => model.is_current)
    if (currentModel) {
      currentModelKey.value = currentModel.key
    }
  } catch (error) {
    console.error('加载可用模型失败:', error)
  }
}

const changeModel = async () => {
  try {
    await setCurrentAIModel(currentModelKey.value)
    alert('模型切换成功')
  } catch (error) {
    console.error('切换模型失败:', error)
    alert('切换模型失败')
  }
}

const saveConfig = async () => {
  try {
    await updateAIConfig(aiConfig.value)
    showConfigDialog.value = false
    alert('配置保存成功')
  } catch (error) {
    console.error('保存配置失败:', error)
    alert('保存配置失败')
  }
}

const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

const formatTime = (timestamp: string) => {
  return new Date(timestamp).toLocaleString('zh-CN')
}

const selectPrefix = (prefix: string) => {
  // 如果当前问题为空，直接添加前缀
  if (!currentQuestion.value.trim()) {
    currentQuestion.value = `${prefix} `
  } else {
    // 如果当前问题不为空，在开头添加前缀
    if (!currentQuestion.value.startsWith(prefix)) {
      currentQuestion.value = `${prefix} ${currentQuestion.value}`
    }
  }
  showPrefixDialog.value = false
}

const renderMarkdown = (text: string) => {
  if (!text) return ''
  try {
    // 配置marked选项
    marked.setOptions({
      breaks: true, // 支持换行
      gfm: true // 支持GitHub风格的Markdown
    })
    return marked(text)
  } catch (error) {
    console.error('Markdown渲染失败:', error)
    return text // 如果渲染失败，返回原文本
  }
}

// 获取当前对话名称
const getCurrentConversationName = () => {
  if (!currentConversationId.value) return ''
  
  const currentSession = conversationSessions.value.find(s => s.id === currentConversationId.value)
  return currentSession ? currentSession.title : '新对话'
}

// 监听当前session变化，加载对话历史
const loadCurrentSessionHistory = async () => {
  if (currentSessionId.value) {
    try {
      const response = await getSessionConversations(currentSessionId.value)
      conversationHistory.value = []
      
      // 将历史记录转换为前端格式
      for (const item of (response as unknown as any[])) {
        conversationHistory.value.push({
          type: item.message_type,
          content: item.content,
          timestamp: item.timestamp
        })
      }
      
      await scrollToBottom()
    } catch (error) {
      console.error('加载对话历史失败:', error)
    }
  } else {
    // 如果没有当前会话，清空对话历史
    conversationHistory.value = []
  }
}

// 监听currentSessionId变化
watch(currentSessionId, (newSessionId) => {
  if (newSessionId) {
    loadCurrentSessionHistory()
  } else {
    conversationHistory.value = []
  }
})

// 生命周期
onMounted(async () => {
  await loadAIConfig()
  await loadAvailableModels()
  await loadConversationHistory()
})
</script>

<style scoped>
.ai-chat {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  background: transparent;
  position: relative;
  max-height: 100%;
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: #ffffff;
  border-bottom: 1px solid #e5e7eb;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
  border-radius: 12px 12px 0 0;
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.chat-header h3 {
  margin: 0;
  color: #374151;
  font-weight: 600;
  font-size: 18px;
}

.current-conversation-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
}

.conversation-label {
  color: #6b7280;
  font-weight: 500;
}

.conversation-name {
  color: #059669;
  font-weight: 600;
  background: #ecfdf5;
  padding: 2px 8px;
  border-radius: 4px;
  border: 1px solid #d1fae5;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.model-selector {
  display: flex;
  align-items: center;
  gap: 8px;
}

.model-selector label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.model-select {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  background: white;
  min-width: 150px;
}

.analysis-section {
  padding: 20px;
  border-bottom: 1px solid #eee;
  background: #f8f9fa;
}

.analysis-content {
  margin-bottom: 20px;
}

.analysis-text {
  white-space: pre-wrap;
  line-height: 1.6;
  color: #333;
}

.suggested-questions h5 {
  margin: 0 0 10px 0;
  color: #666;
}

.question-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.question-btn {
  padding: 8px 16px;
  background: #e3f2fd;
  border: 1px solid #2196f3;
  border-radius: 20px;
  color: #2196f3;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.question-btn:hover {
  background: #2196f3;
  color: white;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  background: #f7f7f8;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.chat-messages {
  flex: 1;
  padding: 0;
  overflow-y: auto;
  min-height: 0;
}

.message {
  margin: 0;
  display: flex;
  padding: 20px 0;
  border-bottom: 1px solid #f0f0f0;
}

.message.user {
  justify-content: flex-end;
}

.message.ai {
  justify-content: flex-start;
}

.message-content {
  max-width: 100%;
  width: 100%;
  margin: 0 auto;
  padding: 0 24px;
  position: relative;
}

.message.user .message-content {
  background: #f8f9fa;
  color: #374151;
}

.message.ai .message-content {
  background: #ffffff;
  color: #374151;
}

.message-text {
  white-space: pre-wrap;
  line-height: 1.6;
  font-size: 16px;
  color: #374151;
}

/* Markdown样式 */
.markdown-content {
  line-height: 1.6;
}

.markdown-content h1,
.markdown-content h2,
.markdown-content h3,
.markdown-content h4,
.markdown-content h5,
.markdown-content h6 {
  margin: 16px 0 8px 0;
  font-weight: 600;
  color: #333;
}

.markdown-content h1 {
  font-size: 1.5em;
  border-bottom: 2px solid #e0e0e0;
  padding-bottom: 8px;
}

.markdown-content h2 {
  font-size: 1.3em;
  border-bottom: 1px solid #e0e0e0;
  padding-bottom: 6px;
}

.markdown-content h3 {
  font-size: 1.1em;
}

.markdown-content p {
  margin: 8px 0;
}

.markdown-content ul,
.markdown-content ol {
  margin: 8px 0;
  padding-left: 24px;
}

.markdown-content li {
  margin: 4px 0;
}

.markdown-content blockquote {
  margin: 12px 0;
  padding: 8px 16px;
  border-left: 4px solid #2196f3;
  background: #f8f9fa;
  color: #666;
}

.markdown-content code {
  background: #f1f3f4;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 0.9em;
}

.markdown-content pre {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 12px 0;
  border: 1px solid #e0e0e0;
}

.markdown-content pre code {
  background: none;
  padding: 0;
  border-radius: 0;
}

.markdown-content table {
  border-collapse: collapse;
  width: 100%;
  margin: 12px 0;
}

.markdown-content th,
.markdown-content td {
  border: 1px solid #e0e0e0;
  padding: 8px 12px;
  text-align: left;
}

.markdown-content th {
  background: #f8f9fa;
  font-weight: 600;
}

.markdown-content strong {
  font-weight: 600;
  color: #333;
}

.markdown-content em {
  font-style: italic;
  color: #666;
}

.markdown-content a {
  color: #2196f3;
  text-decoration: none;
}

.markdown-content a:hover {
  text-decoration: underline;
}

.markdown-content hr {
  border: none;
  border-top: 1px solid #e0e0e0;
  margin: 16px 0;
}

/* 建议问题在聊天区域的样式 */
.suggested-questions-in-chat {
  margin: 20px 0;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
}

.suggested-questions-header {
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  font-size: 14px;
}

/* 打字指示器 */
.typing-indicator {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 8px 12px;
  background: #f0f0f0;
  border-radius: 12px;
}

.typing-indicator .dot {
  width: 8px;
  height: 8px;
  background: #999;
  border-radius: 50%;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator .dot:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator .dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.message-time {
  font-size: 12px;
  opacity: 0.7;
  margin-top: 5px;
}

.chat-input {
  padding: 24px;
  border-top: 1px solid #e5e7eb;
  background: #ffffff;
  position: sticky;
  bottom: 0;
  z-index: 100;
  border-radius: 0 0 12px 12px;
}

.input-container {
  display: flex;
  gap: 12px;
  align-items: flex-end;
  max-width: 100%;
  margin: 0 auto;
  position: relative;
}

.prefix-selector {
  position: absolute;
  top: -40px;
  left: 0;
}

.prefix-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  transition: all 0.2s;
}

.prefix-btn:hover {
  background: #e0e0e0;
  border-color: #ccc;
}

.prefix-icon {
  font-size: 16px;
  color: #888;
}

.prefix-dialog {
  max-width: 400px !important;
}

.prefix-list {
  margin: 20px 0;
}

.prefix-item {
  padding: 16px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: 10px;
  background: #f8f9fa;
}

.prefix-item:hover {
  border-color: #2196f3;
  background: #e3f2fd;
  transform: translateY(-2px);
}

.prefix-name {
  font-size: 16px;
  font-weight: 600;
  color: #2196f3;
  margin-bottom: 8px;
  font-family: monospace;
}

.prefix-description {
  color: #666;
  font-size: 14px;
  line-height: 1.4;
}

.prefix-example {
  margin-top: 8px;
  color: #888;
  font-size: 13px;
  font-style: italic;
}

.question-input {
  flex: 1;
  padding: 16px 20px;
  border: 1px solid #d1d5db;
  border-radius: 24px;
  resize: none;
  font-family: inherit;
  font-size: 16px;
  line-height: 1.5;
  background: #ffffff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  min-height: 56px;
  max-height: 200px;
}

.send-btn {
  padding: 16px 24px;
  background: #10a37f;
  color: white;
  border: none;
  border-radius: 24px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.send-btn:hover:not(:disabled) {
  background: #1976d2;
}

.send-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.config-button {
  position: absolute;
  top: 20px;
  right: 20px;
}

.config-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  padding: 30px;
  border-radius: 8px;
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
}

.dialog-content h4 {
  margin: 0 0 20px 0;
  color: #333;
}

.config-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  color: #666;
  font-weight: 500;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.dialog-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-primary {
  background: #2196f3;
  color: white;
}

.btn-primary:hover {
  background: #1976d2;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #5a6268;
}

.btn-outline {
  background: transparent;
  color: #2196f3;
  border: 1px solid #2196f3;
}

.btn-outline:hover {
  background: #2196f3;
  color: white;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 对话会话样式 */
.conversation-sessions {
  padding: 20px;
  border-bottom: 1px solid #eee;
  background: #f8f9fa;
}

.conversation-sessions h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.session-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.session-item {
  padding: 12px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
  min-width: 200px;
}

.session-item:hover {
  border-color: #2196f3;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.session-item.active {
  border-color: #2196f3;
  background: #e3f2fd;
}

.session-title {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.session-time {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

</style> 